package com.zhonghui.HandlerInterceptor;

import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.StringUtils;
import com.zhonghui.common.core.config.RedisUtils;
import com.zhonghui.common.core.exception.TokenCheckException;
import com.zhonghui.model.User;
import com.zhonghui.service.config.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zhonghui.common.core.constant.FwConstants.USER_LOGIN_TOKEN;

@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String header = request.getHeader("Authorization");
        String s = redisUtils.get(USER_LOGIN_TOKEN + header);
        if (StringUtils.isNullOrEmpty(s)){
            throw new TokenCheckException("请登录");
        }

        User user = JSONUtil.toBean(s, User.class);
        AuthUser.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
